<template>
  <div class="containers">
    <div class="container">
      <div class="handle-box">
        <el-select v-model="take" style="width: 120px;" @change="getDataPage" placeholder="请选择类型" size="mini" class="mr10">
          <el-option v-for="item in navlists" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="state" style="width: 120px;" @change="getDataPage" placeholder="请选择类型" size="mini" class="mr10">
          <el-option v-for="item in navlist" :key="item.id" :label="item.name" :value="item.id"
            v-if="item.name != '已完成1'">
          </el-option>
        </el-select>
        <el-select v-model="pay_type" style="width: 120px;" @change="getDataPage" placeholder="请选择类型" size="mini" class="mr10">
          <el-option v-for="item in paylist" :key="item.id" :label="item.name" :value="item.id"
            v-if="item.id != 1 && item.id != 2">
          </el-option>
        </el-select>

        <el-select v-model="timeType" placeholder="请选择" size="mini" style="width: 100px;" @change="getDataPage">
          <el-option
            label="下单时间"
            :value="0">
          </el-option>
          <el-option
            label="发货时间"
            :value="1">
          </el-option>
        </el-select>
        <el-date-picker class="mr10"  v-model="value2" type="datetimerange" :picker-options="pickerOptions" style="width: 250px;"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="mini" align="right"
          @change="changeTime">
        </el-date-picker>
        <el-input v-model="keyword" style="width: 240px;" placeholder="订单号/用户电话/收货人/商品名称" class="handle-input mr10" size="mini"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="getDataPage"  size="mini">搜索</el-button>
        <el-button type="primary" @click="exportExcel" size="mini">导出</el-button>
        <el-button type="primary" size="mini" @click.native="$refs.filElem.click()">
          导入
          <input type="file" ref="filElem" @change="onChange" id="file" v-show="false">
        </el-button>

        <el-button type="primary" @click="dTemplate" size="mini" plain>下载导入模版</el-button>


      </div>

      <el-table :data="tableData" class="table" ref="multipleTable" header-cell-class-name="table-header" size="mini" border
        @selection-change="handleSelectionChange" v-loading="loading" id="out-table" row-key="order" :height="$tableHight"
       >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table :data="props.row.goods" border size="mini" style="width: 100%">
              <el-table-column label="商品图" width="100" align="center">
                <template slot-scope="scope">
                  <el-image class="table-td-thumb" :src="scope.row.img" :preview-src-list="[scope.row.img]"></el-image>
                </template>
              </el-table-column>
              <el-table-column label="商品名称" prop="name" show-overflow-tooltip></el-table-column>
              <el-table-column label="商品数量" prop="number" width="100"></el-table-column>
              <el-table-column label="商品规格" prop="attributes" width="150"></el-table-column>
              <el-table-column label="商品价格" prop="price" width="100"></el-table-column>
              <el-table-column label="成本价" prop="discount" width="100"></el-table-column>
              <el-table-column label="商品分区" width="150">
                <template slot-scope="scope">
                  {{ getpartition(scope.row.partition_id) }}
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="order" label="订单号" show-overflow-tooltip width="180"></el-table-column>
        <el-table-column prop="money" label="金额"></el-table-column>
        <!-- <el-table-column prop="pv" label="PV值"></el-table-column> -->
        <el-table-column label="购买用户"  show-overflow-tooltip width="110">
          <template slot-scope="scope">
            {{ scope.row.user.nickname }}
          </template>
        </el-table-column>
        <el-table-column prop="user.mobile" label="用户电话" width="110" show-overflow-tooltip></el-table-column>
        <el-table-column label="收货人" align="center">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="收货人电话" align="center" width="120">
          <template slot-scope="scope">
            {{ scope.row.mobile }}
          </template>
        </el-table-column>
        <el-table-column label="收货地址" show-overflow-tooltip width="220">
          <template slot-scope="scope">
            {{ scope.row.address }}
          </template>
        </el-table-column>

        <el-table-column label="支付方式" align="center">
          <template slot-scope="scope">
            {{
              ['消费券', '补贴券', '资产积分', '绿色积分记录', '权益值', '贡献值','云仓积分'][scope.row.pay_type]
            }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center">
          <template slot-scope="scope">

            <el-tag size="mini" :type="scope.row.state == 8 ? 'danger' : 'success'">{{
              ["待付款", "待发货", "待收货", "待评价", "完成", "售后",'','','已取消'][
              scope.row.state
              ]
            }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="提货方式" align="center">
          <template slot-scope="scope">
            {{ ["快递", "自提"][scope.row.take] }}
          </template>
        </el-table-column>
        <el-table-column label="下单时间" align="center" width="160">
          <template slot-scope="scope" v-if="scope.row.pay_time">
            {{ $clearTimer(scope.row.pay_time) }}
          </template>
        </el-table-column>
        <el-table-column label="发货时间" align="center" width="160">
          <template slot-scope="scope" v-if="scope.row.state!= 1 && scope.row.state!= 8">
            {{ $clearTimer(scope.row.deliver_time) }}
          </template>
        </el-table-column>



        <el-table-column label="操作"  align="center" width="160" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" v-if="scope.row.state != 1" @click="handleEdit(scope.row, scope.row.state)">详情</el-button>
            <el-button size="mini" type="text" v-if="scope.row.state == 1" @click="handleEdit(scope.row, state)">发货</el-button>
            <el-button size="mini" type="text" v-if="scope.row.state == 1" @click="cancelOrder(scope.row, state)">取消订单</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange"
          :current-page="query.pageIndex" :page-sizes="[20, 30, 40, 50]" :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import excel from "../../utils/excel.js";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  name: "basetable",
  data() {
    return {
      partition: [],
      query: {
        pageIndex: 1,
        pageSize: 20,
      },
      timeType:0,
      state: 0,
      upload: "",
      editVisible: false,
      pageTotal: 0,
      imageUrl: "",
      videoUrl: "",
      type: 0,
      take: -1,
      navlist: [
        { id: 0, name: "全部" },
        { id: 1, name: "待发货" },
        { id: 2, name: "待收货" },
        { id: 3, name: "完成" },
        { id: 4, name: "已完成1" },
        { id: 5, name: "售后" },
        { id: 8, name: "已取消" },
      ],
      navlists: [
        { id: -1, name: "全部" },
        { id: 0, name: "快递" },
        { id: 1, name: "自提" },
      ],
      paylist: [
        { id: -1, name: "全部" },
        { id: 0, name: "余额" },
        { id: 1, name: "积分" },
        { id: 2, name: "微信" },
        { id: 3, name: "支付宝" },
        { id: 4, name: "银行卡" },
      ],
      pay_type: -1,
      keyword: "",
      loading: false,
      tableData: [
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value2: "",
      start_time: "",
      end_time: "",
    };
  },
  created() {
    this.getData();
  },
  methods: {
    getDataPage() {
      this.query.pageIndex = 1
      this.getData();

    },
    getpartition(id) {
      try {
        let arr = this.partition;
        return arr.filter((item) => item.ID == id)[0].name;
      } catch (error) {
        return "原分区已被删除"
      }

    },
    setImg(row) {
      return;
    },
    copy(row) {
      // 创建一个input框
      const input = document.createElement("input");
      // 将指定的DOM节点添加到body的末尾
      document.body.appendChild(input);
      // 设置input框的value值为复制的值
      const address = row;
      input.setAttribute("value", address);
      // 选取文本域中的内容
      input.select();
      // copy的意思是拷贝当前选中内容到剪贴板
      // document.execCommand（）方法操纵可编辑内容区域的元素
      // 返回值为一个Boolean，如果是 false 则表示操作不被支持或未被启用
      if (document.execCommand("copy")) {
        document.execCommand("copy");
      }
      // 删除这个节点
      document.body.removeChild(input);
      // 弹窗：复制成功
      this.$message.success("复制成功");
      //
    },
    // 导入导出方式  核心代码
    // export function acceptExportData (data) {

    // }
    onChange(event) {
      console.log(event, '5555')
      const inputFile = this.$refs.filElem.files[0];
      var formdata = new FormData()
      if (inputFile) {
        formdata.append('file', inputFile)
        this.$http({
          url: this.mainurl + 'admin/logistics/',
          method: 'post',
          headers: {
            'Content-Type': 'multipart/form-data',
            'token': localStorage.getItem('admin_token_sys')
          },
          data: formdata,
          dataType: "json",
          cache: false, //上传文件无需缓存
          processData: false, //用于对data参数进行序列化处理 这里必须false
          contentType: false, //必须
        }).then(res => {
          console.log(res,'123123')
          if (res.errno == 0) {
            this.$message.success('导入成功，订单已发货')
            this.getData()
          } else {
            this.$message.success(res.data.errmsg)
          }
        })

      }
    },
    exportExcel() {
      var token = localStorage.getItem('admin_token_sys')
      //导出
      this.$http({
        url: this.mainurl + 'admin/order/',
        method: 'get',
        responseType: 'blob',
        params: {
          pay_type: this.pay_type,
          start_time: this.start_time,
          end_time: this.end_time,
          take: this.take,
          page: this.query.pageIndex,
          size: this.query.pageSize,
          state: this.state,
          keyword: this.keyword,
          code: 1,
        },

        headers: {
          'Content-Type': 'application/json',
          token: token
        }
      }).then(res => {

        try {
          FileSaver.saveAs(
            new Blob([res.data], { type: "application/octet-stream;charset=utf-8" }), "订单.xlsx")
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, res.data);
        }
      })
    },
    //修改size值
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.getData();
    },
    dTemplate() {
      // 创建只包含所需字段的模板数据
      const templateData = [
        { "订单号": "", "快递单号": "","物流公司": "" }
      ];

      // 创建工作表
      const ws = XLSX.utils.json_to_sheet(templateData);

      // 创建工作簿
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

      // 写入文件
      const wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
      });

      try {
          FileSaver.saveAs(
              new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
              "订单导入模版.xlsx"
          );
      } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    //获取数据
    getData() {
      this.loading = true;
      this.request("admin/order/", "get", {
        pay_type: this.pay_type,
        start_time: this.start_time,
        end_time: this.end_time,
        take: this.take,
        page: this.query.pageIndex,
        size: this.query.pageSize,
        state: this.state,
        keyword: this.keyword,
        type: this.start_time ? this.timeType : ''
      }).then((res) => {
        // console.log(res)
        this.tableData = res.data.data;
        this.pageTotal = res.data.total;
      });
      this.loading = false;
      this.request("admin/partition/", "get", { page: 1, size: 50 }).then(
        (res) => {
          this.partition = res.data.data;
        }
      );
    },
    // 发货
    handleEdit(e, state) {
      this.$router.push({
        path: "/order/orderDetails",
        query: { id: e.order, state: state },
      });
    },
    // 订单取消
    cancelOrder(row) {
      this.$prompt('请在下方输入取消理由', '确定要取消吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /\S/,
        inputErrorMessage: '内容不能为空'
      }).then(({ value }) => {
        this.request("admin/cancelOrder/", "post", { order: row.order,reason:value }).then(
          (res) => {
            if(res.errno==0) {
              this.$message.success(res.errmsg);
              this.getData()
            }
          }
        );

      }).catch(() => {
        // 用户取消操作
      })
    },
    cancel() {
      this.getData();
    },

    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.request("admin/order/", "delete", { ID: row.ID }).then((res) => {
          if (res.errno == 0) {
            this.$message.success(res.errmsg);
            this.tableData.splice(index, 1);
            this.getData();
          } else {
            this.$message.error(res.errmsg);
          }
        });
      });
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 添加
    addregion() {
      this.$router.push({ path: "/commodity/addgoods" });
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getData();
    },
    changeTime(e) {
      //时间
      console.log(e);
      try {
        this.start_time = this.formatDate(e[0]);
        this.end_time = this.formatDate(e[1]);
      } catch (error) {
        this.start_time = "";
        this.end_time = "";
      }

      this.getData();
    },
    formatTen(num) {
      return num > 9 ? num + "" : "0" + num;
    },
    formatDate(date) {
      var date = new Date(date);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();
      return (
        year +
        "-" +
        this.formatTen(month) +
        "-" +
        this.formatTen(day) +
        " " +
        this.formatTen(hour) +
        ":" +
        this.formatTen(minute) +
        ":" +
        this.formatTen(second)
      );
    },
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.el-upload--text {
  width: 200px !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;

  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  /* width: 100px; */
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 178px;
  display: block;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
  border-radius: 4px;
}

/* 设置分页按钮样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.namelist {
  margin-left: 10px;
}

/* #file{
  width:0px;
  height: 10px;
  opacity: 0;
} */

/* 使用 /deep/ 或 >>> 来穿透 scoped 样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #f2f2f2;
  /* 设置表头颜色 */
  color: #333;
  /* 设置表头文字颜色 */
}

</style>
